const { secret, tokenExpires } = require('../conf')
var jwt = require('jsonwebtoken');

exports.createToken = (user) => {
  return jwt.sign(user, secret, { expiresIn: tokenExpires });
}

exports.verifyToken = (token) => {
  try {
    var decoded = jwt.verify(token, secret);
  } catch (error) {

  } finally {
    return decoded
  }
}

exports.getUser = (token) => {
  return jwt.decode(token);
}

exports.mkPager = (pageNo, pageSize) => {
  // select * from loan limt 0,5   0--第一条，5---5条
  // 1===> 0
  // 2===> 5
  // 3===> 10
  pageSize = parseInt(pageSize)
  return {
    start: (pageNo - 1) * pageSize,
    size: pageSize
  }
}

// 验证必填字段是否传入
exports.checkNulValue = (bodyObj, checkList) => {
  for (let item of checkList) {
    if (bodyObj[item] === undefined || bodyObj[item] === null || bodyObj[item] === '') {
      return {
        result: false,
        data: {
          key: item,
          value: bodyObj[item]
        }
      }
    }
  }
  return {
    result: true
  }

}

const fs = require('fs')
// 判断文件是否存在
exports.fileExit = filePath => {
  try {
    fs.accessSync(filePath)
    return true
  } catch (error) {
    return false
  }
}